{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.3"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "source": [
    "# 切片\n",
    "\n",
    "- 切片指从现有列表中获取一个子列表\n",
    "- 一般创建一个列表时，变量的名字会使用复数"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "## 列表的索引可以是负数\n",
    "\n",
    "如果索引是负数，则从后向前获取元素，`-1` 表示倒数第一个，`-2` 表示倒数第二个，以此类推"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = ['Issac','Qihan Wu','Yupeng Du','Mariah','Acker']\n",
    "print(f'students[-1] = {students[-1]}')\n",
    "print(f'students[-2] = {students[-2]}')"
   ]
  },
  {
   "source": [
    "## 通过切片来获取指定的元素\n",
    "\n",
    "- 语法：`列表[起始:结束]`\n",
    "    - 通过切片获取元素时，会包含起始位置的元素，不会包括结束位置的元素\n",
    "- 做切片操作时，总会返回一个新的列表，不会影响原来的列表\n",
    "- 起始位置和结束位置的索引可以省略不写\n",
    "    - 如果省略结束位置，则会一直截取到最后\n",
    "    - 如果省略开始位置，则会从第一个元素开始截取\n",
    "    - 如果开始位置和结束位置全部省略，则相当于创建了一个列表的副本"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = ['Issac','Qihan Wu','Yupeng Du','Mariah','Acker']\n",
    "print(f'students[0:3] = {students[0:3]}')\n",
    "print(f'students[2:5] = {students[2:5]}')\n",
    "print(f'students[3:] = {students[3:]}')\n",
    "print(f'students[:4] = {students[:4]}')\n",
    "print(f'students[:] = {students[:]}')"
   ]
  },
  {
   "source": [
    "- 语法：`列表[起始:结束:步长]`\n",
    "    - 步长表示每次获取元素的间隔，默认是 `1`\n",
    "    - 步长不能是 `0`，但是可以是负数\n",
    "    - 如果是负数，则会从列表的后部向前边取元素"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = ['Issac','Qihan Wu','Yupeng Du','Mariah','Acker']\n",
    "print(f'students[0:5:2] = {students[0:5:2]}')\n",
    "print(f'students[0:5:-2] = {students[0:5:-2]}')\n",
    "print(f'students[4:0:-2] = {students[4:0:-2]}')\n",
    "print(f'students[-1:-4:-3] = {students[-1:-5:-3]}')"
   ]
  }
 ]
}